from collections import OrderedDict
from futu import *
import sys


class Update():
    """
    Update Class
    """
    @staticmethod                # 静态方法无需实例化，导入后直接用 Update.update_price()    
    def update_price(stock_list):

        dict = OrderedDict([('00123', '越秀地产'), ('00813', '世茂房地产'), ('02777', '富力地产'), ('00410', 'SOHO中国'), ('02007', '碧桂园'),
                            ('03377', '远洋集团'), ('01776', '广发证券'), ('06837','海通证券'), ('03383', '雅居乐集团'), ('06886', '华泰证券'),
                            ('03900', '绿城中国'), ('00688', '中国海外发展'), ('02628','中国人寿'), ('01918', '融创中国'), ('03333', '中国恒大'),
                            ('06098', '碧桂园服务'), ('01313', '华润水泥控股'), ('01813','合景泰富集团'), ('00604', '深圳控股'), ('06049', '保利物业'),
                            ('01109', '华润置地'), ('01638', '佳兆业集团'), ('00939','建设银行'), ('01288', '农业银行'), ('02669', '中海物业'),
                            ('02018', '瑞声科技'), ('01905', '海通恒信'), ('02689','玖龙纸业'), ('01233', '时代中国控股'), ('00772', '阅文集团'),
                            ('06030', '中信证券'), ('03908', '中金公司'), ('01299','友邦保险'), ('00700', '腾讯控股'), ('00005', '汇丰控股'),
                            ('09988', '阿里巴巴-SW'), ('00883','中国海洋石油'), ('02318', '中国平安')
                            ])

    # 通过futu-api取行情，list example: ['HK.00123','HK.00410','SH.600480','SZ.300219']

        # df = Update.getPriceFUTU(['HK.00123', 'HK.00410', 'HK.00813', 'HK.02777', 'HK.00939', 'HK.01288', 'HK.02628', 'HK.00688', 'HK.02669',
        #            'HK.06837', 'HK.06886', 'HK.01776', 'HK.01109', 'HK.02007', 'HK.03333', 'HK.03383', 'HK.01313', 'HK.00604',
        #            'HK.03900', 'HK.03377', 'HK.01918', 'HK.01638', 'HK.06098', 'HK.01813', 'HK.00772', 'HK.02018', 'HK.01905',
        #            'HK.01233', 'HK.02689', 'HK.01109', 'HK.06030', 'HK.03908', 'HK.01299', 'HK.00700', 'HK.00005', 'HK.09988',
        #            'HK.00883', 'HK.02318', 'HK.06049', ])
        df = Update.getPriceFUTU(stock_list)
        data = df.to_json(orient="split")

        return data

    def getPriceFUTU(codelist):
        pricelist = []
        ratelist = []
        quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
        priceT = quote_ctx.get_market_snapshot(codelist)
        quote_ctx.close()
        
        df = priceT[1][['code', 'last_price', 'prev_close_price', 'volume', 'volume_ratio',
                        'turnover', 'turnover_rate', 'dividend_ratio_ttm']]
        df['change_rate'] = (df['last_price'] / df['prev_close_price'] - 1) * 100
        df['code'] = df.code.map(lambda x: x[3:])
        return df



